package com.heba;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.LocaleList;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.heba.greenmulu.BuildConfig;
import com.heba.greenmulu.R;
import com.mob.MobSDK;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.litepal.LitePal;

import java.io.File;
import java.util.Locale;

import cn.jpush.android.api.JPushInterface;

/**
 * ATApp
 * <p>
 * Created by shenghao on 2016/12/06.
 */
public class ATApp extends Application {

    /**
     * context
     */
    private static Context context;

    /**
     *
     */
    public static final String AppID = "wx0652ea77a14a5f24";
    public static final String AppSecret = "49d97f8b48810b92b71c1ae717d66825";
    /**
     *
     */
    public static IWXAPI api;

    /**
     *
     *
     */
    public static String CosSecretId = "AKIDXx9fwxLFW4NVO2SbWCdpqc9RUIrBh4ez";
    public static String CosSecretKey = "LNBOfjX4KK4YlhNmulNipgIfnfIgohMn";

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.white, R.color.colorGreen);//全局设置主题颜色
                ClassicsHeader classicsHeader = new ClassicsHeader(context);
                classicsHeader.setProgressResource(R.drawable.refresh_loading_animation);
                classicsHeader.setEnableLastTime(false);
                //获取经典头部的控件,隐藏刷新文字
                TextView tvTitle = classicsHeader.findViewById(ClassicsHeader.ID_TEXT_TITLE);
                ImageView ivArrow = classicsHeader.findViewById(ClassicsHeader.ID_IMAGE_ARROW);
                ImageView ivProgress = classicsHeader.findViewById(ClassicsHeader.ID_IMAGE_PROGRESS);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivArrow.getLayoutParams();
                params.leftMargin = 0;
                params.rightMargin = 0;
                ivProgress.setLayoutParams(params);
                tvTitle.setVisibility(View.GONE);
                return classicsHeader;//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                ClassicsFooter classicsFooter = new ClassicsFooter(context);
                classicsFooter.setDrawableSize(20);
                classicsFooter.setProgressResource(R.drawable.refresh_loading_animation);

                //获取经典底部的控件,隐藏刷新文字
                TextView tvTitle = classicsFooter.findViewById(ClassicsHeader.ID_TEXT_TITLE);
                ImageView ivArrow = classicsFooter.findViewById(ClassicsHeader.ID_IMAGE_ARROW);
                ImageView ivProgress = classicsFooter.findViewById(ClassicsHeader.ID_IMAGE_PROGRESS);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivArrow.getLayoutParams();
                params.leftMargin = 0;
                params.rightMargin = 0;
                ivProgress.setLayoutParams(params);
                tvTitle.setVisibility(View.GONE);
                return classicsFooter;
            }
        });
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();

        /**
         * 數據庫
         */
        LitePal.initialize(this);

        /**
         * share SDK
         */
        MobSDK.init(this);
//        MobSDK.submitPolicyGrantResult(true, null);

        /**
         * facebook init
         */
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);

        /**
         * JPush init
         */
        JPushInterface.setDebugMode(BuildConfig.DEBUG);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush

        /**
         *
         */
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        Debug.Log("ATApp", "start");
        /**
         *
         */
        context = getApplicationContext();
        Cfg.setContext(getApplicationContext());

        /**
         *
         */
        setAppLanguage();

        /**
         *
         */
        regToWx();

        /**
         *
         */
        initImageLoader(getApplicationContext());

        /**
         *
         */
        updateRefreshContent();
    }

    /**
     * getContext
     *
     * @return
     */
    public static Context getContext() {
        return context;
    }

    /**
     * getApplication
     *
     * @return
     */
    public static ATApp getApplication() {
        return (ATApp) context.getApplicationContext();
    }

    /**
     */
    private void regToWx() {
        //通过工厂获取实例
        api = WXAPIFactory.createWXAPI(this, AppID, true);
        api.registerApp(AppID);
    }

    /**
     *
     * @param context
     */
    public static void initImageLoader(Context context) {
//      http://site.com/image.png // from Web
//      file:///mnt/sdcard/image.png // from SD card
//      file:///mnt/sdcard/video.mp4 // from SD card (video thumbnail)
//      content://media/external/images/media/13 // from content provider
//      content://media/external/video/media/13 // from content provider (video thumbnail)
//      assets://image.png // from assets
//      drawable:// + R.drawable.img // from drawables (non-9patch images)

        // This configuration tuning is custom. You can tune every option, you may tune some of them,
        // or you can create default configuration by
        //  ImageLoaderConfiguration.createDefault(this);
        // method.
        File cacheDir = StorageUtils.getCacheDirectory(context);  //缓存文件路径
        ImageLoaderConfiguration config =
                new ImageLoaderConfiguration.Builder(context)
                        .threadPriority(Thread.NORM_PRIORITY - 2) //设置当前线程的优先级
                        .threadPoolSize(3)   //线程池内加载的数量
                        .denyCacheImageMultipleSizesInMemory()
                        .diskCacheFileNameGenerator(new Md5FileNameGenerator())  //文件命名
//                        .diskCacheFileCount(100)   //设置缓存文件的数量,超过数量后,old将被删除
//                        .diskCacheSize(200 * 1024 * 1024)   //文件緩存大小  设置 200Mb sd卡(本地)缓存的最大值
                        .memoryCache(new WeakMemoryCache())//內存緩存
//                        .memoryCache(new LRULimitedMemoryCache(2 * 1024 * 1024)) //內存緩存大小
                        .diskCache(new UnlimitedDiskCache(cacheDir))  //文件目錄
                        .tasksProcessingOrder(QueueProcessingType.LIFO)   //default
                        .writeDebugLogs() // 打印debug log
                        .build();  //开始构建
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }

    /**
     */
    public static void setAppLanguage() {
        Debug.Log("setAppLanguage", Cfg.Language + "");
        Resources resources = context.getApplicationContext().getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Locale locale = getSetLanguageLocale();
        if (locale.getLanguage().toLowerCase().equals("zh")) {
            Cfg.Leng = 1;
            Cfg.Language = 2;
        } else {
            Cfg.Leng = 0;
            Cfg.Language = 1;
        }
        config.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleList localeList = new LocaleList(locale);
            LocaleList.setDefault(localeList);
            config.setLocales(localeList);
            context.getApplicationContext().createConfigurationContext(config);
            Locale.setDefault(locale);
        }
        resources.updateConfiguration(config, dm);
    }

    /**
     *
     * @return
     */
    public static Locale getSetLanguageLocale() {

        switch (Cfg.Language) {
            case 0:
                return Locale.getDefault();
            case 1:
                return Locale.ENGLISH;
            case 2:
                return Locale.CHINESE;
            default:
                return Locale.ENGLISH;
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    public void launchAppDetail(String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) return;

            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     */
    public static void updateRefreshContent() {
        ClassicsHeader.REFRESH_HEADER_PULLING = context.getString(R.string.header_pulling);
        ClassicsHeader.REFRESH_HEADER_REFRESHING = context.getString(R.string.header_refreshing);
        ClassicsHeader.REFRESH_HEADER_LOADING = context.getString(R.string.header_loading);
        ClassicsHeader.REFRESH_HEADER_RELEASE = context.getString(R.string.header_release);
        ClassicsHeader.REFRESH_HEADER_FINISH = context.getString(R.string.header_finish);
        ClassicsHeader.REFRESH_HEADER_FAILED = context.getString(R.string.header_failed);
        ClassicsHeader.REFRESH_HEADER_UPDATE = context.getString(R.string.header_update);
        ClassicsHeader.REFRESH_HEADER_UPDATE = context.getString(R.string.header_update);
        ClassicsHeader.REFRESH_HEADER_SECONDARY = context.getString(R.string.header_secondary);

        ClassicsFooter.REFRESH_FOOTER_PULLING = context.getString(R.string.footer_pulling);
        ClassicsFooter.REFRESH_FOOTER_RELEASE = context.getString(R.string.footer_release);
        ClassicsFooter.REFRESH_FOOTER_LOADING = context.getString(R.string.footer_loading);
        ClassicsFooter.REFRESH_FOOTER_REFRESHING = context.getString(R.string.footer_refreshing);
        ClassicsFooter.REFRESH_FOOTER_FINISH = context.getString(R.string.footer_finish);
        ClassicsFooter.REFRESH_FOOTER_FAILED = context.getString(R.string.footer_failed);
        ClassicsFooter.REFRESH_FOOTER_NOTHING = context.getString(R.string.footer_nothing);
    }
}